<template>
  <div class="add-card">
    <header class="add-header">
      <el-page-header
        :content="id ? '修改月卡' : '添加月卡'"
        @back="$router.back()"
      />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">车辆信息</div>
        <div class="form">
          <el-form
            ref="carInfoForm"
            label-width="100px"
            :model="carInfoForm"
            :rules="carInfoRules"
          >
            <el-form-item label="车主姓名" prop="personName">
              <el-input v-model="carInfoForm.personName" />
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNumber">
              <el-input v-model="carInfoForm.phoneNumber" />
            </el-form-item>
            <el-form-item label="车辆号码" prop="carNumber">
              <el-input v-model="carInfoForm.carNumber" />
            </el-form-item>
            <el-form-item label="车辆品牌" prop="carBrand">
              <el-input v-model="carInfoForm.carBrand" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="form-container">
        <div class="title">最新一次月卡缴费信息</div>
        <div class="form">
          <el-form
            :model="feeForm"
            ref="feeForm"
            :rules="feeFormRules"
            label-width="100px"
          >
            <el-form-item
              label="有效日期"
              prop="payTime"
              style="margin-right: 20px"
            >
              <el-date-picker
                v-model="feeForm.payTime"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy/MM/dd"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
            <el-form-item label="支付金额" prop="paymentAmount">
              <el-input v-model="feeForm.paymentAmount" />
            </el-form-item>
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="feeForm.paymentMethod">
                <el-option
                  v-for="item in payMethodList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="reset">重置</el-button>
        <el-button type="primary" @click="confirmAdd">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { reqPostCardAPI, reqGetDetailAPI, reqPutCardAPI } from "@/api/card";
export default {
  name: "addMonthCard",
  data() {
    return {
      // 第一个表单，存放车辆信息
      // 给第一个表单:model
      carInfoForm: {
        personName: "",
        phoneNumber: "",
        carNumber: "",
        carBrand: "",
      },
      carInfoRules: {
        personName: [
          { required: true, message: "车主姓名不可为空", trigger: "blur" },
          {
            min: 2,
            max: 5,
            message: "长度在 2 到 20 个字符",
            trigger: "blur",
          },
        ],
        phoneNumber: [
          { required: true, message: "手机号码不可为空", trigger: "blur" },
          {
            pattern: /^(1[3-9]\d{9}$)/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        carNumber: [
          {
            pattern: /^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{5}$/,
            message: "请输入正确的车牌号",
            trigger: "blur",
          },
          { required: true, message: "请输入车牌号", trigger: "blur" },
        ],
        carBrand: [
          { required: true, message: "请输入车辆品牌", trigger: "blur" },
          // 自定义校验
          {
            validator: this.validatorcarBrand,
            trigger: "blur",
          },
        ],
      },

      feeForm: {
        payTime: [], // 支付时间
        paymentAmount: "", // 支付金额
        paymentMethod: "", // 支付方式
      },
      // 缴费规则
      feeFormRules: {
        payTime: [
          {
            required: true,
            message: "请选择支付时间",
          },
        ],
        paymentAmount: [
          {
            required: true,
            message: "请输入支付金额",
            trigger: "blur",
          },
        ],
        paymentMethod: [
          {
            required: true,
            message: "请选择支付方式",
            trigger: "change",
          },
        ],
      },
      // 支付方式列表
      payMethodList: [
        {
          id: "Alipay",
          name: "支付宝",
        },
        {
          id: "WeChat",
          name: "微信",
        },
        {
          id: "Cash",
          name: "线下",
        },
      ],
    };
  },
  created() {
    // 此处不会影响到添加方法的数据，因为只有在编辑时才会调用getCardDetail方法
    if (this.id) {
      this.getCardDetail();
    }
  },
  methods: {
    validatorcarBrand: (rule, value, callback) => {
      // rule:用不到
      // callback:不管成功还是失败都要调用
      // 正确：callback()
      // 错误：callback(new Error("请输入正确的车辆品牌"))
      console.log(value, "validatorcarBrand的值");
      if (value.length < 1) {
        callback(new Error("请输入正确的车辆品牌"));
      } else {
        callback();
      }
    },
    // 点击确定按键
    confirmAdd() {
      this.$refs.carInfoForm.validate((flag) => {
        if (!flag) {
          console.log("第一步没通过");
          return;
        } else {
          this.$refs.feeForm.validate(async (flag) => {
            if (!flag) {
              console.log("第二步没通过");
              return;
            }
            // 组装对象，使用展开运算符
            // 这样会拿到九个数据 与接口需要的8个数据不吻合，报404的错误，因此需要移除payTime这条数据
            const requestData = {
              ...this.carInfoForm,
              ...this.feeForm,
              cardStartDate: this.feeForm.payTime[0],
              cardEndDate: this.feeForm.payTime[1],
            };
            // 删除payTime
            delete requestData.payTime;
            if (this.id) {
              await reqPutCardAPI(requestData);
              this.$notify.success("修改成功");
            } else {
              delete requestData.carInfoId;
              delete requestData.rechargeId;
              try {
                await reqPostCardAPI(requestData);
                this.$notify.success("添加成功");
              } catch (error) {
                console.dir(error);
                this.$notify.error("添加失败");
              }
            }
            // 返回上个页面
            this.$router.back();
          });
        }
      });
    },
    // 重置表单且清空爆红，resetFields只能清空prop绑定的表单域
    reset() {
      this.$refs.carInfoForm.resetFields();
      this.$refs.feeForm.resetFields();
    },
    async getCardDetail() {
      const id = this.$route.query.id;
      const { data } = await reqGetDetailAPI(id);
      console.log(data, 15);
      const { personName, phoneNumber, carNumber, carBrand, carInfoId } = data;
      this.carInfoForm = {
        personName,
        phoneNumber,
        carNumber,
        carBrand,
        carInfoId,
      };
      const {
        rechargeId,
        paymentMethod,
        paymentAmount,
        cardStartDate,
        cardEndDate,
      } = data;
      this.feeForm = {
        payTime: [cardStartDate, cardEndDate],
        paymentAmount,
        paymentMethod,
        rechargeId,
      };
    },
  },
  computed: {
    id() {
      return this.$route.query.id;
    },
  },
};
</script>

<style scoped lang="scss">
.add-card {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }
      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
    .preview {
      img {
        width: 100px;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
